﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core;
using Medianamik.Core.Sugar;
using Medianamik.Globalization;
using Medianamik.UI.Controls;
using Telerik.Web.UI;
using System.Security.Permissions;
using Roles = Medianamik.Core.Security.Roles;

namespace Medianamik.UI.NodeManagement
{
    public partial class ListList : BaseModuleListPage
    {
        private Guid? _typeId;
        protected Guid TypeId
        {
            get
            {
                if (_typeId == null)
                {
                    _typeId = Guid.Empty;
                    var id = Request.QueryString[DefaultParamNames.TypeID];
                    if (id != null)
                    {
                        Guid g;
                        if (StringHelper.IsGuid(id, out g))
                        {
                            _typeId = g;
                        }
                    }
                }
                return _typeId.Value;
            }
        }

        protected override GridActionOptions GridActionOptions
        {
            get
            {
                return GridActionOptions.Activation | GridActionOptions.Edit | GridActionOptions.Delete;
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            var listTypeSelectedWindow = new BaseModalWindow { ID = "ListTypeSelectorWindow" };
            
            if (!IsPostBack)
            {
                listTypeSelectedWindow.OnClientClose = "onNodeTypeSelected";
                listTypeSelectedWindow.IconUrl = "/Medianamik/images/Icones/Ico_AjoutPage.gif";
                listTypeSelectedWindow.ReloadOnShow = true;
                listTypeSelectedWindow.Width = Unit.Pixel(400);
                listTypeSelectedWindow.Height = Unit.Pixel(200);
            }

            MyWindowManager.Windows.Add(listTypeSelectedWindow);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindComboBox();
                Grid.PageSize = GetQueryStringValue<int?>("nb") ?? 20;
                Grid.CurrentPageIndex = (GetQueryStringValue<int?>("p") ?? 1 - 1) * Grid.PageSize;
                Form.DefaultButton = RefreshButton.UniqueID;
            }
            var url = "/Medianamik/ModalWindows/ListTypeSelectorWindow.aspx";
            if (cbTypes.SelectedIndex != 0)
            {
                url += "?" + Medianamik.Core.DefaultParamNames.TypeID + "=" + cbTypes.SelectedValue;
            }
            lnkAddNode.NavigateUrl = url;
            addNodeUpdatePanel.Update();
        }

        protected override void GridNeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            Guid typeId;
            if (cbTypes.SelectedIndex != 0 && StringHelper.IsGuid(cbTypes.SelectedValue, out typeId))
            {
                int count;
                var filter = FilterBox.Text.Trim();
                if (filter.Length == 0)
                {
                    Grid.DataSource = NodeManager.GetPagedNodesByType(typeId, MedianamikProperties.Name,
                                                                      CurrentEditionCulture.Name,
                                                                      Grid.CurrentPageIndex + 1, Grid.PageSize,
                                                                      out count);
                }
                else
                {
                    Grid.DataSource = NodeManager.GetPagedNodesByType(typeId, MedianamikProperties.Name,
                                                                      CurrentEditionCulture.Name,
                                                                      filter,
                                                                      Grid.CurrentPageIndex + 1, Grid.PageSize,
                                                                      out count);
                }
                Grid.VirtualItemCount = count;
                FilterPlaceHolder.Visible = true;
            }
            else
            {
                Grid.DataSource = null;
                Grid.VirtualItemCount = 0;
                FilterPlaceHolder.Visible = false;
            }
        }

        protected void GridItemDataBound(object sender, GridItemEventArgs e)
        {
            /*var gridItem = e.Item as GridDataItem;
            if (gridItem != null)
            {
                var node = (Node)gridItem.DataItem;

                var nodeActivationButton = e.Item.FindControl("btnNodeActivation") as NodeActivationButton;
                if (nodeActivationButton != null &&
                    !Roles.IsUserInRole(MedianamikRoles.ElementActivationManagement))
                    nodeActivationButton.Enabled = false;

                var editButton = e.Item.FindControl("EditButton") as LockButton;
                if(editButton != null)
                {
                    editButton.Enabled = Roles.IsUserInRole(MedianamikRoles.ManageContent);
                    editButton.ImageUrl = "/medianamik/images/Icones/Ico_Edition.gif";
                    editButton.LockedOrDisabledImageUrl = "/medianamik/images/Icones/Ico_EditionInactif.gif";
                    editButton.NavigateUrl = String.Format("{0}?id={1}",
                    ManagementURL, node.ID);
                    editButton.NodeId = node.ID;
                    editButton.RequestFailed += LockRequestFailed;
                    editButton.Attributes.Add("title", Translator.Translate("Medianamik_global", "Action_EditTooltip"));
                }

                var deleteButton = e.Item.FindControl("deleteNodeButton") as LockButton;
                if (deleteButton != null)
                {
                    deleteButton.Enabled = deleteButton.Enabled
                                           //&& Roles.UserHasRight(node, SecurityLevels.Delete) pas besoin puisque appliqué au bouton
                                           &&
                                           (node.Instances.Exists(CurrentEditionCulture.Name) ||
                                            MedianamikContext.Current.MedianamikUser.CanDeleteAllInstancesOfANode)
                                           &&
                                           (!node.HasChildren ||
                                            MedianamikContext.Current.MedianamikUser.CanDeleteNodeBranch);
                }

            }
            else */
            if (e.Item is GridPagerItem)
            {
                var lbl = e.Item.FindControl("ChangePageSizeLabel") as Label;
                if (lbl != null)
                    lbl.Text = Translator.Translate("Medianamik_Global", "GridChangePageSize");
            }
        }

        [PrincipalPermission(SecurityAction.Assert, Role = "ElementActivationManagement ")]
        protected void btnNodeActivation_Command(object sender, CommandEventArgs e)
        {
            NodeManager.SetNodeActiveStatus(new Guid(e.CommandArgument.ToString()),
                                            CurrentEditionCulture,
                                            e.CommandName.ToLowerInvariant() == "activate");

            Grid.Rebind();
        }

        protected void LockLink_RequestFailed(object sender, CommandEventArgs e)
        {
            Grid.Rebind();
            LockInfoTooltip.ObjectId = new Guid((string)e.CommandArgument);
            LockInfoTooltip.DataBind();
            LockInfoTooltip.Show();
        }

        protected void LockInfoTooltip_LockDeleted(object sender, EventArgs e)
        {
            //TODO : Rediriger vers le noeud dévérouillé (besoin dans EventArgs)
            //grdNodes.Rebind();
            //gridUpdatePanel.Update();
        }

        protected void SelectType(object sender, EventArgs e)
        {
            Grid.CurrentPageIndex = 0;
            Grid.Rebind();
        }

        protected void FilterList(object sender, EventArgs e)
        {
            Grid.Rebind();
        }

        protected override RadGrid Grid
        {
            get { return NodeList; }
        }

        protected override UpdatePanel GridUpdatePanel
        {
            get { return updPanel; }
        }

        protected override string ManagementURL
        {
            get { return "ListManagement.aspx"; }
        }

        protected void BindComboBox()
        {
            var types = NodeTypeManager.GetAllTypes(false)
                .Where(t => !t.IsSystem
                          && t.Listable
                          && Roles.UserHasRight(t, Core.Security.SecurityLevels.Read))
                .OrderBy(t => t.LocalizedName);
            if (types.Count() > 0)
            {
                cbTypes.DataSource = types;
                cbTypes.DataTextField = "LocalizedName";
                cbTypes.DataValueField = "ID";
                cbTypes.DataBind();
                cbTypes.Items.Insert(0,
                                     new ListItem(Translator.Translate("Medianamik_ModalWindows",
                                                                       "TypeSelector_LabelType")));
                if (TypeId != Guid.Empty && types.Any(t => t.ID == TypeId))
                {
                    cbTypes.SelectedValue = TypeId.ToString();
                    FilterPlaceHolder.Visible = true;
                }
                else
                {
                    cbTypes.SelectedIndex = 0;
                    FilterPlaceHolder.Visible = false;
                }
            }
            else
            {
                lnkAddNode.Visible = false;
                cbTypes.Visible = false;
                NoTypeMessage.Visible = true;
            }
        }

        protected override string ReturnUrl
        {
            get { return "/medianamik/contentmanagement/listlist.aspx"; }
        }

        protected string  BuildReturnUrl()
        {
            var url = ReturnUrl;
            
            if(Grid.PageSize != 20)
                url = url.AddParam("nb", Grid.PageSize);

            if(Grid.CurrentPageIndex != 0)
                url = url.AddParam("p", Grid.CurrentPageIndex + 1);

            return "&returnurl=" +(cbTypes.SelectedIndex > 0 ? 
                url.AddParam(DefaultParamNames.TypeID, cbTypes.SelectedValue) : 
                url).UrlEncodeBase64();
        }
    }
}
